package org.jtb.quickr;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.log4j.Logger;

class FlickrUrl {
    private static Logger logger = Logger.getLogger(FlickrUrl.class.getName());
    
    private URL url;
    private String baseUrl;
    private Map<String,String> args;
    
    public FlickrUrl(String baseUrl) {
        this(baseUrl, new HashMap<String, String>());
    }

    public FlickrUrl(String serviceUrl, Map<String,String> args) {
        setBaseUrl(serviceUrl);
        setArgs(new HashMap<String, String>(args));
    }

    protected URL buildUrl() throws QuickrException {
        Map<String,String> args = getArgs();
        
        StringBuffer u = new StringBuffer(32);
        u.append(getBaseUrl());
        
        if (args.size() > 0) {
            u.append("?");
        }
        
        for (Iterator<String> i = args.keySet().iterator(); i.hasNext(); ) {
            String key = i.next();
            String val = args.get(key);
            u.append(key);
            u.append("=");
            u.append(val);
            if (i.hasNext()) {
                u.append("&");
            }
        }
        
        try {
            URL url = new URL(u.toString());
            if (logger.isDebugEnabled()) {
                logger.debug("url: " + url);
            }
            return url;
        } catch (MalformedURLException mfue) {
            mfue.printStackTrace();
            throw new QuickrException("could not create URL", mfue);
        }
    }
    
    public URL getUrl() throws QuickrException {
        // lazy initialization
        if (url == null) {
            url = buildUrl();
        }
        return url;
    }
       
    public String toString() {
        try {
            return getUrl().toString();
        } catch (QuickrException qe) {
            throw new RuntimeException(qe);
        }
    }

    protected String getBaseUrl() {
        return baseUrl;
    }

    private void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    protected Map<String, String> getArgs() {
        return Collections.unmodifiableMap(args);
    }

    protected void putArg(String key, String val) {
        args.put(key, val);
    }
    
    private void setArgs(Map<String, String> args) {
        this.args = args;
    }
}
